const http = require("http");
const url = require("url");
const fs = require("fs");

const ctxPath = process.env.CONTEXTPATH | "";

http
  .createServer(function (req, res) {
    const filepath = url.parse(req.url, true).pathname;

    console.log("origin filepath => " + filepath);

    var filename = ".";

    if (ctxPath && filepath.indexOf(ctxPath) != 0) {
      filepath = filepath.replace("/" + ctxPath, "");
    }
    if (filepath.indexOf("/site") != 0) {
      filename += "/site";
    }

    if (
      !filepath.endsWith("/") &&
      !filepath.endsWith(".js") &&
      !filepath.endsWith(".css")
    ) {
      if (filepath.endsWith(".png")) {
        filename += "/images" + filepath;
      } else {
        filename += filepath;
      }
    } else {
      filename += "/";
    }

    if (filepath.endsWith("/")) {
      filename += "index.html";
    }

    if (
      !filepath.endsWith("/") &&
      !filepath.endsWith(".png") &&
      filepath.indexOf(".") >= 0
    ) {
      filename += filepath.substr(filepath.lastIndexOf("/") + 1);
    }

    console.log("filepath, filename => " + filepath + ", " + filename);

    // check for only API call
    if (filename.endsWith("/getImages")) {
      subpath = filename.substr(0, filename.lastIndexOf("/")).substr(6);
      searchpath = "site/images";
      if (subpath != "" && subpath != "/") {
        console.log("subpath : " + subpath);
        searchpath += subpath;
      }

      imageList = fs.readdirSync(searchpath);
      // sort by date modified
      imageList.sort(function (a, b) {
        return (
          fs.statSync(searchpath + "/" + a).mtime.getTime() -
          fs.statSync(searchpath + "/" + b).mtime.getTime()
        );
      });
      if (subpath != "" && subpath != "/") {
        imageList.unshift("..");
      }
      files = { images: imageList };
      return res.end(JSON.stringify(files));
    } else {
      // simple http sever
      filename = filename.replace("%20", " ");
      fs.readFile(filename, function (err, data) {
        if (err) {
          res.writeHead(404, { "Content-Type": "text/html" });
          return res.end("404 " + filename + "Not Found");
        }
        return res.end(data);
      });
    }
  })
  .listen(4000);
